<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\decrypt\weixin\wxBizDataCrypt;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use think\cache\driver\Redis;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'wxLogin', 'getWechatPhone'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        // $stateList=model('app\admin\model\User')->getStateList();
        
        

    }

    /**
     * 会员中心
     */
    public function index()
    {
        
        $user = $this->auth->getUser();
        // print_r($user['endtime']-time());die;
        // if($user['endtime']-time()<0){
        //     //会员到期更新会员状态
        //     model('app\common\model\User')->where('id',$this->auth->id)->update(['isvip'=>0]);
        //     $user = $this->auth->getUser();
        // }
        $user['group'] = model('app\common\model\UserGroup')->where('id', $user['group_id'])->find();
        $user['level'] = model('app\common\model\user\Level')->where('id', $user['level_id'])->find();
        $user['viptype'] = model('app\admin\model\Membertype')->where('id', $user['vip_id'])->find();
        //        var_dump($this->auth->getUser());exit();
        $this->success('', $user);
    }

    public function wxLogin()
    {
        $post = $this->request->request();
        // 登录项目
        $code = $this->request->request("code");
        $recommend = $this->request->request("recommend", '0');

        $user_sn = $this->request->request("user_sn", '');
        $money = $this->request->request("money", 0);
        $goods_id = $this->request->request("goods_id", 0);
        $config = get_addon_config('epay');

        // \think\Log::record("=============：{$out_trade_no}，推荐人：$recommend");

        $params = [
            'appid' => $config['wechat']['miniapp_id'],
            'secret' => $config['wechat']['app_secret'],
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        //         var_dump(  $config['wechat']);exit();
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        // var_dump($result);
        $json = (array)json_decode($result['msg'], true);
          $json['openid'] = 'oq3Ax5Wn36dFcyVkUcEWG8sqxuNE';
        if (!isset($json['openid'])) {
            $this->error($json['errmsg']);
        }
        $openid = trim($json['openid']);
        $user = model('app\common\model\User')->get(['openid' => $openid]);
        $info['mobile'] = '';
        //        if(!$user){
        //            $decrypt = new wxBizDataCrypt($config['wechat']['miniapp_id'], $json['session_key']);
        //            $decrypt->decryptData($post['encryptedData'], $post['iv'], $data);
        //            $data = (array)json_decode($data, true);
        //            $mobile = $data['phoneNumber'];
        //            $info['mobile'] = $mobile;
        //        }
        if ($user && $user['id'] != 0) {

            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user['id']);
            $type = 'login';
        } else {
            $info['recommend'] = $recommend;
            //            var_dump($info);exit();
            $ret = $this->auth->register2($openid, $info);
            //            if ($user_to){
            //                model('app\common\model\Recommend')->insert([
            //                    'user_id'   => $user_to['id'],
            //                    'number'    => '-1',
            //                    'last_num'  =>$user_to['recommend_num'],
            //                    'state'     =>2,
            //                    'mote'      =>'注册减少',
            //                    'to_user_id'=>$this->auth->id,
            //                    'createtime'=>time(),
            //                ]);
            //                $info['recommend'] = $user_to['id'];
            //                $user_to->setDec('recommend_num');
            //            }
            $type = 'register';

            $redis = new Redis();

            $lottery_time = \config('site.lottery_time');
            $lottery_time = bcmul($lottery_time, 60);

            $key = 'lotteryTime_' . $this->auth->id;

            $redis->set($key, '1', $lottery_time);
        }

        if ($recommend && $money && $goods_id && $user['recommend'] == $recommend) {

            model('app\common\model\Coupon')
                ->where('from_user_id', $recommend)
                ->where('goods_id', $goods_id)
                ->where('status', 1)
                ->update(['status' => 4]);

            model('app\common\model\Coupon')::create([
                'user_id' => $this->auth->id,
                'goods_id' => $goods_id,
                'coupon_sn' => 'CO' . time() . rand(10, 99) . $this->auth->id,
                'discount' => $money,
                'from_user_id' => $recommend,
            ]);
        }

        $data = ['userinfo' => $this->auth->getUserinfo(), 'type' => $type];
        $this->success(__('Logged in successful'), $data);
    }




    public function getWechatPhone()
    {
        $post = $this->request->request();
        // 登录项目
        $code = $this->request->request("code");

        $recommend = $this->request->request("recommend", 0);
        $config = get_addon_config('epay');
        $params = [
            'appid' => $config['wechat']['miniapp_id'],
            'secret' => $config['wechat']['app_secret'],
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        // var_dump( $config);exit();
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        $json = (array)json_decode($result['msg'], true);
        if (!isset($json['openid'])) {
            $this->error($json['errmsg']);
        }

        $decrypt = new wxBizDataCrypt($config['wechat']['miniapp_id'], $json['session_key']);
        $decrypt->decryptData($post['encryptedData'], $post['iv'], $data);
        $data = (array)json_decode($data, true);
        // 开始登录
        $mobile = $data['phoneNumber'];

        // print_r($json);
        $this->success('success', $mobile);
    }



    // public function getWechatPhone()
    //     {
    //         $post = $this->request->request();

    //         $config = get_addon_config('epay');

    //         $user = $this->auth->getUser();

    //         $params = [
    //             'appid' => $config['wechat']['miniapp_id'],
    //             'secret' => $config['wechat']['app_secret'],
    //             'js_code' => $post['code'],
    //             'grant_type' => 'authorization_code'
    //         ];
    // //         var_dump(  $config['wechat']);exit();
    //         $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

    //         $json = (array)json_decode($result['msg'], true);
    // //          $json['openid'] = 'o27MJ7apex2pxGOqJT66xiA84AJ0';
    //         if (!isset($json['openid'])) {
    //             $this->error($json['errmsg']);
    //         }

    //         if(!$user){
    //             $decrypt = new wxBizDataCrypt($config['wechat']['miniapp_id'], $json['session_key']);
    //             $decrypt->decryptData($post['encryptedData'], $post['iv'], $data);
    //             $data = (array)json_decode($data, true);
    //             $mobile = $data['phoneNumber'];
    //             $info['mobile'] = $mobile;
    //         }


    //     }


    public function lotteryStatus()
    {
        $redis = new Redis();

        $key = 'lotteryTime_' . $this->auth->id;

        $row['lottery'] = '';

        if ($redis->get($key)) {
            $row['lottery'] = 1;
        }



        $this->success('success', $row);
    }



    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');

        $mobile = $this->request->post('mobile');

        $avatar = $this->request->post('avatar', '');
        if ($avatar) {



            $user->avatar = $avatar;
        }

        if ($mobile) {



            $user->mobile = $mobile;
        }
        if ($nickname) {

            $user->nickname = $nickname;
        }
        $user->save();
        $user->group = model('app\common\model\UserGroup')->where('id', $user['group_id'])->find();
        $this->success('修改成功', $user);
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function browse()
    {
        $state = $this->request->request('state', 'browse');
        $list = model('app\common\model\Collect')
            ->with(['song'])
            ->where('user_id', $this->auth->id)
            ->where('state', $state)
            ->order('createtime', 'desc')
            ->paginate();
        $this->success('success', $list);
    }

    public function buyList()
    {
        $state = $this->request->request('state', '');

        if ($state == 'myself') { //自己购买
            $where = ['user_id' => $this->auth->id];
        } else {
            $where = ['recommend' => $this->auth->id];
        }
        $list = model('app\common\model\buy\Song')->with(['songRow'])->where($where)->paginate();
        $this->success('success', $list);
    }

    public function partner()
    {
        $user = $this->auth->getUserinfo();
        $user['recommend_count'] = model('app\common\model\User')
            ->where('recommend', $this->auth->id)
            ->count();
        $user['money_count'] = model('app\common\model\MoneyLog')
            ->where('user_id', $this->auth->id)
            ->whereNotLike('memo', '%提现%')
            ->where('type', 2)
            ->count();
        $user['money_total'] = model('app\common\model\MoneyLog')
            ->where('user_id', $this->auth->id)
            ->whereNotLike('memo', '%提现%')
            ->where('type', 2)
            ->sum('money');

        $user['bank_count'] = model('app\common\model\Bank')
            ->where('user_id', $this->auth->id)
            ->count();

        $user['withdrawal_count'] = model('app\common\model\Withdrawal')
            ->where('user_id', $this->auth->id)
            ->count();
        $user['withdrawal_money'] = model('app\common\model\Withdrawal')
            ->where('status', 2)
            ->where('user_id', $this->auth->id)
            ->sum('money');
        $this->success('success', $user);
    }

    public function partnerShop()
    {
        $user = $this->auth->getUserinfo();
        $user['recommend_count'] = model('app\common\model\User')
            ->where('recommend', $this->auth->id)
            ->count();


        $user['money_count'] = model('app\common\model\MoneyLog')
            ->where('user_id', $this->auth->id)
            ->whereNotLike('memo', '%提现%')
            ->where('type', 2)
            ->count();

        $user['bank_count'] = model('app\common\model\Bank')
            ->where('user_id', $this->auth->id)
            ->count();

        $user['withdrawal_count'] = model('app\common\model\Withdrawal')
            ->where('user_id', $this->auth->id)
            ->count();
        $user['withdrawal_money'] = model('app\common\model\Withdrawal')
            ->where('status', 2)
            ->where('user_id', $this->auth->id)
            ->sum('money');


        $this->success('success', $user);
    }

    public function withdrawalLog()
    {
        $withdrawalLog = model('app\common\model\Withdrawal')
            //            ->where('status',2)
            ->where('user_id', $this->auth->id)
            ->order('createtime desc')
            ->paginate();

        $this->success('success', $withdrawalLog);
    }

    public function recommendLog()
    {
        $list = model('app\common\model\User')
            ->where('recommend', $this->auth->id)
            ->paginate();
        $this->success('success', $list);
    }
    public function moneyLog()
    {
        $type = $this->request->request('type', 2);

        $list = model('app\common\model\MoneyLog')
            ->with(['user'])
            ->where('user_id', $this->auth->id)
            ->where('type', $type)
            ->whereNotLike('memo', '%提现%')
            ->order('createtime desc')
            ->paginate();
        $this->success('success', $list);
    }

    public function addressList()
    {
        $list = model('app\common\model\Address')->where('user_id', $this->auth->id)->paginate();
        $this->success('success', $list);
    }

    public function createAddress()
    {
        $id = $this->request->request('id', 0);
        $name = $this->request->request('name', '');
        $phone = $this->request->request('phone', '');
        $provinces = $this->request->request('provinces', '');
        $cities = $this->request->request('cities', '');
        $districts = $this->request->request('districts', '');


        $address = $this->request->request('address', '');
        $is_default = $this->request->request('is_default', 0);
        if (!$name || !$provinces || !$cities || !$districts || !$address) {
            $this->error('请填写完整信息');
        }
        if (!Validate::regex($phone, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $Address = model('app\common\model\Address');
        if ($id > 0) {
            $Address =  model('app\common\model\Address')->where('id', $id)->find();
            if (!$Address) $this->error('地址不存在');
        }

        $Address->is_default = $is_default;
        if ($is_default == 1) {
            model('app\common\model\Address')
                ->where('user_id', $this->auth->id)
                ->update(['is_default' => 0]);
        }
        $Address->name = $name;
        $Address->user_id = $this->auth->id;
        $Address->phone = $phone;
        $Address->provinces = $provinces;
        $Address->districts = $districts;
        $Address->cities = $cities;
        $Address->address = $address;

        $Address->save();
        $this->success('success', $Address);
    }

    //地址详情
    public function addressDelite($id)
    {
        $Address =  model('app\common\model\Address')->where('id', $id)->find();
        $this->success('success', $Address);
    }

    public function addressDefault()
    {
        $Address =  model('app\common\model\Address')
            ->where('is_default', 1)
            ->where('user_id', $this->auth->id)
            ->find();
        $this->success('success', $Address);
    }

    public function setDefault()
    {
        $id = $this->request->request('id', 0);
        $Address =  model('app\common\model\Address')->where('id', $id)->find();
        if (!$Address) $this->error('地址不存在');
        $Address->is_default = 1;
        model('app\common\model\Address')
            ->where('user_id', $this->auth->id)
            ->where('id', '<>', $id)
            ->update(['is_default' => 0]);
        $Address->save();
        $this->success('success');
    }

    public function delAddress($id)
    {
        $Address =  model('app\common\model\Address')->where('id', $id)->find();
        if (!$Address) $this->error('地址不存在');
        $Address->delete();
        $this->success('success');
    }

    /** 获取地区
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getArea()
    {
        $pid = $this->request->request("pid", 0);
        $data = Db::name('area')
            ->field('id,name')
            ->where('pid', $pid)->select();
        $this->success('success', $data);
    }

    public function collectList()
    {
        $type = $this->request->request('type', 1);
        $list = model('collectgoods')
            ->with('goods')
            ->where('user_id', $this->auth->id)
            ->where('type', $type)
            ->paginate();

        $this->success('success', $list);
    }

    public function lottery()
    {
        $list = model('lottery')
            ->field('id')
            ->with(['goods'])
            ->where('lottery.status', 1)->select();
        $this->success('success', $list);
    }

    public function pushLottery()
    {
        $lottery_id = $this->request->request('lottery_id', '');

        $user = $this->auth->getUser();

        $redis = new Redis();

        $key = 'lotteryTime_' . $this->auth->id;

        if (!$redis->get($key)) {

            $this->error('暂无抽奖次数');
        }

        $key_lock = 'pushLottery:' . $this->auth->id;

        $lockAcquired = $redis->handler()->setnx($key_lock, 1);

        if ($lockAcquired) {
            $ser  = $redis->handler()->expire($key_lock, 10);
        } else {
            $this->error('请求过快');
        }


        $lottery = model('lottery')
            ->field('id,scale,phone,goods_id')
            ->with(['goods'])
            ->where('lottery.status', 1)
            ->select();

        $sum_scale = model('lottery')

            ->where('status', 1)
            ->sum('scale');


        if (!$lottery) $this->error('游戏不存在');




        $redis->rm($key);


        $lotteryArr = [];

        foreach ($lottery as $k => $v) {
            $scale = 0;
            if ($v['phone']) {
                $arr = explode(',', $v['phone']);

                if (in_array($user['mobile'], $arr)) {

                    $arr = [
                        'user_id' => $user['id'],
                        'goods_id' => $v['goods_id'],
                        'createtime' => time(),
                    ];

                    model('app\common\model\Lotterylog')->insert($arr);

                    $this->success('中奖', $v);
                }
            }
            if ($v['scale'] > 0) {
                $arr = $this->lotteryArr($v['id'], $v['scale']);
                $lotteryArr = array_merge($lotteryArr, $arr);
            }
        }

        if ($sum_scale < 100) {
            $arr = $this->lotteryArr(0, bcsub(100, $sum_scale));
            $lotteryArr = array_merge($lotteryArr, $arr);
        }
        shuffle($lotteryArr);



        $id = $lotteryArr[array_rand($lotteryArr)];

        if ($id == 0) {
            $this->error('未中奖');
        }



        $fin = model('lottery')
            ->field('id,goods_id')
            ->with(['goods'])
            ->where('lottery.id', $id)
            ->find();

        //        dump($fin);exit();

        $arr = [
            'user_id' => $user['id'],
            'goods_id' => $fin['goods_id'],
            'createtime' => time(),
        ];

        model('app\common\model\Lotterylog')->insert($arr);
        $this->success('中奖', $fin);

        //        dump($last);exit();
        //
        //        if ($v['scale'] > 0){
        //            $scale = $v['scale'];
        //            $rand = rand(1,100);
        //            if ($scale >= $rand){
        //                $arr = [
        //                    'user_id'=>$user['id'],
        //                    'goods_id'=>$v['goods_id'],
        //                    'createtime'=>time(),
        //                ];
        //
        //                model('app\common\model\Lotterylog')->insert($arr);
        //
        //                $this->success('中奖',$v);
        //            }
        //        }

        $this->error('未中奖');
    }


    public function lotteryArr($goods_id, $num)
    {
        $lotteryArr = [];
        for ($i = 0; $i < $num; $i++) {
            $lotteryArr[$i] = $goods_id;
        }
        return $lotteryArr;
    }

    public function lotteryLog()
    {
        $list = model('app\common\model\Lotterylog')
            ->with(['goods'])
            ->where('user_id', $this->auth->id)
            ->select();

        $this->success('success', $list);
    }




//增加交易量

    /**
     * 增加交易量
     * @return true
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addTradingVolume()
    {
//        sal
        $user_sql=model('app\admin\model\User');

        $user=$user_sql
            ->where('id',$this->auth->id)
            ->find();
        if (empty($user)) {
            throw new Exception("未查询到用户数据!");
        }
        if (empty($user['trading_volume'])) {
            $user->trading_volume=1;
            //是否有推荐人/是否算新用户
            $time=60*60*24*30;
            if (!empty($user['recommend'] && ($user['createtime']-time()<=$time))){
                //返现
                return "返现";
                return true;
            }
        }else{
            $user->trading_volume+=1;
        }
        return true;
    }














}
